(function () {
	etlinking.views.groupDetail = new GroupDetailFunc();

	function GroupDetailFunc () {
		var _self = this;

		_self.init = init;

		var cssClass = {
			selected:"selected"
		};
		var _groupId;
		var socialActions = nsbase.config.actionUrl.social,
        	utilities = nsbase.utility,
        	clientResource = nsbase.resources.clientResource;

		function init(){
      		$(".nav_menu li.Social").addClass(cssClass.selected);
			$(".item_list").arrowSlide();
			 _groupId = utilities.trim($("#txtGroupId").val());
			bindControlHandler();
			initKpiChartArea();
		    initGrid();
		    $(".select_time li[day-range='7']").click();
		}

		function bindControlHandler () {
			$("#btnJoin").click(function () {
	          var sender = $(this);
	          var $container = sender.parent(".operate_btn:first");
	          $container.mask();
	          var param = {
	            group_id: _groupId
	          }
	          nsbase.ajax.request(socialActions.joinGroup,param,function(result){
	            $container.unmask();
	            if(result.success){
	                location.reload();
	            }
	          },function () {
	            $container.unmask();
	          });
		    });

		    $("#btnQuit").click(function () {
				var sender = $(this);
				if(!confirm(clientResource.msgQuitGroupConfirm)){
		            return;
		        }
				var $container = sender.parent(".operate_btn:first");
				$container.mask();
				var param = {
					group_id: utilities.trim($("#txtGroupId").val())
				}
				nsbase.ajax.request(socialActions.quitGroup,param,function(result){
					$container.unmask();
					if(result.success){
						location.reload();
					}
				},function () {
					$container.unmask();
				});
		    });
		}
		function initGrid () {
			var gridConfig = {
				renderTo:"gridContainer",
				height:500,
				rowNumber:true,
				columns:[
					{title:"",dataIndex:"rankchange",width:30,formater:rankingFormatter},
					{title:"",dataIndex:"photo",width:40,formater:photoFormatter},
					{title:clientResource.columnGroupMemberName,dataIndex:"user_name",width:200,align:"left",formater:nameFormatter},
					{title:clientResource.columnGroupCalorie,dataIndex:"calorie",width:150,align:"left",sortable:true,selectable:true,formater:colorieFormatter},
					{title:clientResource.columnGroupMiles,dataIndex:"miles",width:150,sortable:true,selectable:true},
					{title:clientResource.columnGroupSteps,dataIndex:"steps",width:150,sortable:true,selectable:true},
					//{title:"跳数",dataIndex:"jumps",width:125,sortable:true,selectable:true},
					{title:clientResource.columnGroupSleep,dataIndex:"sleeptime",width:150,sortable:true,selectable:true},
					{title:clientResource.columnGroupOperation,dataIndex:"relation",width:60,formater:relationFormatter}
				],
				rowSelectable:"none",
				paggingBar: {
					remote: true,
					pageIndex: 1,
					pageSize: 8
				},
				store:{
					data: {
						groupId: _groupId,
						sortField: "calorie",
						sortDirect: "desc" //asc|desc
					}, 
					url: socialActions.getGroupMembers,
				}
			}
			var gridEvents = nsbase.controls.grid.setting.eventEnums;
			var grid = new nsbase.controls.grid(gridConfig);
			grid.on(gridEvents.rowClick,function(sender,rowData){
				
			});
			grid.on(gridEvents.columnSelectChanged,function(columnEl,rowData){
				
			});
			grid.on(gridEvents.cellClick,function(event,rowData){
				var sender = $(event.target);
				if(sender.is(".add")){
					event.stopPropagation();
					addFriend(rowData.user_id);
				}
			});

			// var dataList = [
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 1, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 1, 'photo': '', 'relation': 1, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': -1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': -1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},

			// ];
			// grid.showData(dataList);

			function rankingFormatter(column, value, obj){
				var rankingEnum = nsbase.enums.rankingEnum.getEnumByValue(value);
				var cssName = rankingEnum.key;
				return '<span class="grid_icon '+ cssName +'"></span>';
			}

			function photoFormatter (column,value,obj) {
				var imgSrc = "../static/images/photo.png";
				if(value){
					imgSrc = value;
				}
				return '<img src="'+ imgSrc +'" width="30" height="30" onError="this.src=\'../static/images/photo.png\';"/>';
			}
			function nameFormatter (column,value,obj) {
				var memberRoleEnum = nsbase.enums.memberRoleEnum.getEnumByValue(obj.role);
				var cssName = memberRoleEnum.key;
				return '<span class="grid_icon" style="width:30px"></span><span class="grid_icon '+ cssName +'" title="'+ memberRoleEnum.text +'"></span>'+ utilities.htmlEncode(value);
			}
			function colorieFormatter (column,value,obj) {
				return '<span class="grid_icon calorie"></span>' + value + ' cal';
			}
			function relationFormatter (column,value,obj) {
				if(nsbase.enums.relationshipEnum.strange == value){
					return '<a href="###" title="'+ clientResource.linkAddFriend +'"><span class="grid_icon add"></span></a>';
				}
				return "";
			}
		}

		function addFriend (friendId) {
			var param = {
            	friendId: friendId
			}
			nsbase.ajax.request(socialActions.addFriend,param,function(result){
            	if(result.success){
                	utilities.errorDialog(clientResource.msgWaitForConfirm);
            	} else{
            		utilities.errorDialog(result.message)
            	}
			},function () {
				utilities.errorDialog(clientResource.msgRequestFail);
			});
		}


		function initKpiChartArea(){
	      $(".select_time li").click(function(){
	        var sender = $(this);
	        if(sender.hasClass(cssClass.selected)) return;

	        $(".select_time li").removeClass(cssClass.selected);
	        sender.addClass(cssClass.selected);
	        var dayRange = sender.attr("day-range");
	        var $timeRange = $(".time_range");
	        $timeRange.children("div").hide();
	        $timeRange.children("div.range_"+ dayRange).show();
	        if(dayRange > 1 ){
		        startDate = utilities.dateFormat(utilities.getDate(-dayRange+1),"yyyy-MM-dd");
		        endDate = utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd");
		        $timeRange.children("div.range_"+ dayRange).text(utilities.stringFormat(clientResource.lblTo,startDate,endDate));
				// 绑定chart 图
				bindKpiItemChart("day",startDate,endDate);
	        } else if(dayRange == 1){
	          var startDate = $("#txtDatePicker").val();
	          // 绑定chart 图
	          bindKpiItemChart("hour",startDate);
	        }
	      });

	      $(".select_kpi li").click(function(){
	        var sender = $(this);
	        if(sender.hasClass(cssClass.selected)) return;

	        sender.parent("ul").find("li").removeClass(cssClass.selected);
	        sender.addClass(cssClass.selected);
	        var dayRange = $(".select_time li.selected").attr("day-range");
	        if(dayRange > 1 ){
	          var startDate = utilities.dateFormat(utilities.getDate(-dayRange+1),"yyyy-MM-dd");
	          var endDate = utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd");
	          // 绑定chart 图
	          bindKpiItemChart("day",startDate,endDate);
	        } else if(dayRange == 1){
	          var startDate = $("#txtDatePicker").val();
	          // 绑定chart 图
	          bindKpiItemChart("hour",startDate);
	        } else if(dayRange == 0){
	          var startDate = $("#txtStartDate").val();
	          var endDate = $("#txtEndDate").val();
	          bindKpiItemChart("day",startDate,endDate);
	        }
	      });

	      // $("#txtDatePicker").datepicker({
	      //   maxDate:-1,
	      //   dateFormat:"yy-mm-dd",
	      //   onSelect:function(dateText,datepicker){
	      //     // 绑定 图
	      //     bindKpiItemChart("hour",dateText);
	      //   }
	      // });
	      $("#txtDatePicker").val(utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd"));
	      $("#txtStartDate").datepicker({
	        maxDate:-1,
	        defaultDate:-6,
	        dateFormat:"yy-mm-dd",
	        onSelect:function(dateText,datepicker){
	          $("#txtEndDate").datepicker("option","minDate",dateText);
	          // 绑定 图
	          bindKpiItemChart("day",dateText,$("#txtEndDate").val());
	        }
	      });
	      $("#txtStartDate").val(utilities.dateFormat(utilities.getDate(-6),"yyyy-MM-dd"));
	      $("#txtEndDate").datepicker({
	        maxDate:-1,
	        minDate:-7,
	        defaultDate:-1,
	        dateFormat:"yy-mm-dd",
	        onSelect:function(dateText,datepicker){
	          $("#txtStartDate").datepicker("option","maxDate",dateText);
	          // 绑定 图
	          bindKpiItemChart("day",$("#txtStartDate").val(),dateText);
	        }
	      });
	      $("#txtEndDate").val(utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd"));
	    }

    	 function bindKpiItemChart (timeUnit, startDate,endDate) {
	      var chartContainer = $("#itemChart .chartContainer");
	      var statType = "";
	      var $kpiObj = $(".select_kpi li.selected");
	      if($kpiObj.attr("stat-type")){
	        statType = $kpiObj.attr("stat-type");
	      }
	      if(!statType){
	        return;
	      }
	      chartContainer.mask();
	      var param = {
	      	group_id:_groupId,
	        start_date:startDate,
	        end_date:endDate,
	        time_Unit:timeUnit,
	        stat_type:statType
	      };
	      var kpiTitle = $kpiObj.text();
	      var kpiSuffic = "";
	      switch(statType){
	        case "calorie":
	          kpiSuffic = clientResource.unitCal;
	          break;
	        case "run":
	          kpiSuffic = clientResource.unitKM;
	          break;
	        case "step":
	          kpiSuffic = clientResource.unitStep;
	          break;
	        default:
	          break;
	      };
	      var chartConfig = {
	          container:chartContainer,
	          chartType:"line",
	          title:kpiTitle,//"卡路里VS个数"||"睡时"
	          xAxis:{series:[]},
	          yAxis:{
	            title: kpiTitle +"("+kpiSuffic+")",
	            series:[]
	          },
	          tooltip:{
	            valueSuffix: kpiSuffic
	          }
	      };
	      nsbase.ajax.request(socialActions.getKpiItemChartData, param, function(result) {
	          chartContainer.unmask();
	          if(result.success){
	            chartConfig.xAxis.series = result.data.xAxis;
	            chartConfig.yAxis.series = result.data.yAxis;
	            createChart(chartConfig);
	          } else {
	            utilities.errorDialog(result.message);
	          }
	        },function(){
	          chartContainer.unmask();
	        });
	    }
		function createChart (option) {
	      // var config = {
	      //     container:"",
	      //     chartType:"column",
	      //     title:"总卡路里消耗",
	      //     subtitle:"最近7天",
	      //     xAxis:[],
	      //     yAxis:{
	      //       title:"",
	      //       series:[]
	      //     },
	      //     tooltip:{
	      //       valueSuffix: 'cal'
	      //     }
	      // };

	      var fontColor="#6b6b6b";
	      var chartOption = {
	          chart: {
	            type: option.chartType,
	            marginTop: 60
	          },
	          colors:['#1CAC00','#06beff','#F88614'],
	          title: {
	            text: option.title,
	            style:{
	              color:fontColor,
	              fontWeight: 'bold'
	            }
	          },
	          credits:{
	            enabled: false
	          },
	          xAxis: {
	            categories: option.xAxis.series,
	            labels:{
	              rotation:-45,
	              step:Math.ceil(option.xAxis.series.length/10)
	            }
	          },
	          yAxis: {
	              title: {
	                  text: option.yAxis.title,
	                  style:{
	                    color:fontColor
	                  }
	              },
	              min:0,
	              plotLines: [{
	                  value: 0,
	                  width: 1,
	                  color: fontColor
	              }]
	          },
	          tooltip: {
	              valueSuffix: option.yAxis.valueSuffix
	          },
	          legend: {
	              //enabled:false,
	              align: 'center',
	              floating:true,
	              verticalAlign: 'top',
	              y: 20,
	              borderWidth: 0
	          },
	          series: option.yAxis.series
	      };
	      if(option.subtitle){
	        chartOption.subtitle = {
	          text: option.subtitle,
	          style:{
	            color:fontColor
	          }
	        };
	      }
	      if(option.xAxis.labels){
	        chartOption.xAxis.labels = option.xAxis.labels;
	      }
	      
	      option.container.highcharts(chartOption);
	    }
	}
})();